import sys, os, time
from PyQt4 import QtGui, QtCore
try:
    import VISA_Agilent_8753c_NA as VV
except:
    pass
import Coil_sp_to_RLM as CC

IdRole = QtCore.Qt.UserRole

class RenderArea(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)

        self.pixmap = QtGui.QPixmap()
        self.pixname = ""
        self.setBackgroundRole(QtGui.QPalette.Base)

    def minimumSizeHint(self):
        return QtCore.QSize(100, 100)

    def sizeHint(self):
        return QtCore.QSize(850, 600)

    def setPixmap(self, pixname):
        if self.pixmap.load(pixname):
            self.pixname = pixname
            print "%s loaded"%pixname
        else:
            if not os.path.exists(pixname):
                print "%s picture not found"%pixname
            else:
                print "%s exists, but can't be loaded"%pixname
        self.update()
        
    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)

        painter.save()
        painter.drawPixmap(10, 10, self.pixmap)

        painter.restore()

        painter.end()

class myLineBox(QtGui.QLineEdit):
    def __init__(self, parent = None):
        QtGui.QLineEdit.__init__(self, parent)
    def keyPressEvent(self, event):
        key = event.key()

        if key in [QtCore.Qt.Key_Down, QtCore.Qt.Key_Up]:
            filelist = os.listdir(".")
            if key == QtCore.Qt.Key_Up:
                filelist = filelist[::-1]
            nowvalue = str(self.text())
            for i in range(len(filelist)):
                if not filelist[i].lower().endswith(".s2p"):
                    continue
                if nowvalue in filelist[i]:
                    bFound = False
                    for j in range(i+1, len(filelist)):
                        if filelist[j].endswith(".s2p"):
                            self.setText(filelist[j])
                            self.selectAll()
                            bFound = True
                            break
                    if bFound: break
        QtGui.QLineEdit.keyPressEvent(self, event)

class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle(self.tr("Basic Drawing"))

        self.s2pname = ""
        self.renderArea = RenderArea()

        plotoptions = (("R",1),("L",2),("Q",3),("K",4),)
        self.plotComboBox = QtGui.QComboBox()
        for plotname,numid in plotoptions:
            self.plotComboBox.addItem(self.tr(plotname), QtCore.QVariant(numid))
        self.plotLabel = QtGui.QLabel(self.tr("&Plot types:"))
        self.plotLabel.setBuddy(self.plotComboBox)

        self.portsCheckBox = QtGui.QCheckBox(self.tr("Two Po&rts:"))
        self.pixLineEdit = myLineBox()
        self.pixLabel = QtGui.QLabel(self.tr("Plot &Name:"))
        self.pixLabel.setBuddy(self.pixLineEdit)

        genS2pButton = QtGui.QPushButton(self.tr("Generate .s2p"))
        resetButton = QtGui.QPushButton(self.tr("reset NA"))
        writeCaliButton = QtGui.QPushButton(self.tr("write Calib to NA"))
        loadCaliButton = QtGui.QPushButton(self.tr("load Calib from NA"))

        self.connect(self.portsCheckBox, QtCore.SIGNAL("toggled(bool)"),
                     self.portsChanged)
        self.connect(self.pixLineEdit, QtCore.SIGNAL("textChanged(const QString &)"),
                     self.s2pNameChanged)
        self.connect(self.plotComboBox, QtCore.SIGNAL("activated(int)"),
                     self.plotChanged)

        self.connect(genS2pButton, QtCore.SIGNAL("clicked()"),
                     self.genS2p)
        self.connect(resetButton, QtCore.SIGNAL("clicked()"),
                     self.resetNA)
        self.connect(writeCaliButton, QtCore.SIGNAL("clicked()"),
                     self.writeCali2NA)
        self.connect(loadCaliButton, QtCore.SIGNAL("clicked()"),
                     self.loadCaliFromNA)
        
        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(self.renderArea, 0, 0, 1, 3)
        mainLayout.addWidget(self.pixLabel,1,0)
        mainLayout.addWidget(self.pixLineEdit, 1,1,1,2)
        mainLayout.addWidget(self.plotLabel, 2,0)
        mainLayout.addWidget(self.plotComboBox,2,1,1,2)
        mainLayout.addWidget(self.portsCheckBox, 3,0)
        mainLayout.addWidget(genS2pButton, 3,1,1,2)
        mainLayout.addWidget(resetButton, 4,0)
        mainLayout.addWidget(writeCaliButton, 4,1)
        mainLayout.addWidget(loadCaliButton, 4,2)
        
        self.setLayout(mainLayout)
        self.plotChanged()
        self.portsChanged(False)
    def resetNA(self):
        try:
            VV.reset()
        except:
            pass
    def writeCali2NA(self):
        try:
            ca = VV.readCaliFromFile()
            VV.writeCali(ca)
        except:
            pass
    def loadCaliFromNA(self):
        try:
            ca = VV.readCali()
            if ca:
                VV.writeCaliToFile(ca)
        except:
            pass
            
    def plotChanged(self):
        value = self.plotComboBox.itemData(self.plotComboBox.currentIndex(), IdRole).toInt()[0]
        comboOptions = {1:"_RvsF.png",2:"_LvsF.png",
                        3:"_QvsF.png",4:"_KvsF.png"}
        pixname = self.s2pname+comboOptions[value]
        if not os.path.exists(self.s2pname):
            print "%s not found"%pixname
            return
        if not os.path.exists(pixname) or os.path.getmtime(self.s2pname)>=os.path.getmtime(pixname):
            print "%s is newer, re-calculating parameters..."%self.s2pname
            self.drawS2p()
        self.renderArea.setPixmap(pixname)
        self.update()
        
    def portsChanged(self, bTwoPorts):
        self.twoPorts = bTwoPorts
        if os.path.exists(self.s2pname):
            self.drawS2p()
        self.plotChanged()
        
    def s2pNameChanged(self, filename):
        self.s2pname = str(filename)
        if len(filename)>2:
            filelist = os.listdir(".")
            for f in filelist:
                if not f.lower().endswith(".s2p"):
                    continue
                if f.startswith(filename):
                    self.pixLineEdit.setText(f)
                    self.pixLineEdit.setSelection(len(filename), len(f)-len(filename))
                    self.s2pname = f
                    break
        self.plotChanged()
    def genS2p(self):
            if os.path.exists(self.s2pname):
                reply = QtGui.QMessageBox.question(self, self.tr("overwrite ?"),
                                           self.tr("file %s already exists, overwrite ?"%self.s2pname), QtGui.QMessageBox.Yes,
                                           QtGui.QMessageBox.No)
                if reply == QtGui.QMessageBox.No:
                    return
            VV.genS2p(self.s2pname)
            self.plotChanged()
    def drawS2p(self):
        CC.drawFile(self.s2pname, self.twoPorts)
    def paintEvent(self,event):
        self.renderArea.update()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
